<template>
    <a-card>
        <a-table
            size="middle"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="false"
            :loading="loading"
            :row-selection="rowSelection"
        >
            <template #bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'field'">
                    <div>
                        <a-input v-model:value="record.field" />
                    </div>
                </template>
                <template v-else-if="column.dataIndex === 'javaType'">
                    <div>
                        <a-select
                            :options="javaTypeData"
                            style="width: 100%;"
                            v-model:value="record.javaType"
                        />
                    </div>
                </template>
            </template>
        </a-table>
    </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Bus } from '@/plugin';
// Api
import { ApiCodeGenerator } from "@/axios/api";
// Model
import { Result } from "@/model/common";
import { DbColumnQuery, DbColumnDTO, EntityField } from "@/model/code_generator";

onMounted(() => {
    Bus.on('refresh_db_column', (_query: any) => {
        if (_query) {
            query = _query;
        }
        refresh();
    })
})

const loading = ref<boolean>(false);
let query: DbColumnQuery = new DbColumnQuery();
const columns = DbColumnDTO.columns;
const dataSource = ref<DbColumnDTO[]>([]);
let selectFields: EntityField[] = [];
const rowSelection = ref({
    columnWidth: 50,
    onChange: (selectedRowKeys: any, selectedRows: DbColumnDTO[]) => {
        selectFields.length = 0;
        selectedRows.forEach((item: DbColumnDTO) => {
            const field = new EntityField();
            field.name = item.field;
            field.type = item.javaType;
            field.comment = item.comment;
            selectFields.push(field);
        });
        Bus.emit('change_selected_db_column', selectFields);
    }
})
const javaTypeData = [
    {
        value: 'String',
        title: 'String',
    },
    {
        value: 'Boolean',
        title: 'Boolean',
    },
    {
        value: 'Integer',
        title: 'Integer',
    },
    {
        value: 'Long',
        title: 'Long',
    },
    {
        value: 'Date',
        title: 'Date',
    },
]

const refresh = () => {
    loading.value = true;
    ApiCodeGenerator.listColumn(query)
        .then((res: Result) => {
            dataSource.value = res.data;
        })
        .finally(() => {
            loading.value = false;
        })
}

const handleFieldName = (record: DbColumnDTO) => {
    console.log(JSON.stringify(record));
}
</script>

<style lang="less" scoped>
</style>